<template>
    <div class="auth-layout">
    <div class="login-card">
        <h3 class="login-title">系统登录</h3>
        <el-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            label-position="left"
            label-width="80px"
        >
            <el-form-item prop="username" label="账号">
                <el-input
                    v-model="loginForm.username"
                    prefix-icon="User"
                    placeholder="请输入账号"
                />
            </el-form-item>
            <el-form-item prop="password" label="密码">
                <el-input
                    v-model="loginForm.password"
                    prefix-icon="Lock"
                    type="password"
                    placeholder="请输入密码"
                    show-password
                />
            </el-form-item>
            <el-form-item prop="captchaCode" label="验证码">
                <el-input
                    v-model="loginForm.captchaCode"
                    prefix-icon="Picture"
                    placeholder="请输入验证码"
                    style="width: 180px; margin-right: 10px"
                />
                <img
                    :src="captcha.image"
                    alt="验证码"
                    class="captcha-image"
                    @click="getCaptcha"
                    title="点击刷新"
                />
            </el-form-item>
            <el-form-item>
                <el-checkbox v-model="autoLogin">自动登录</el-checkbox>
            </el-form-item>
            <el-form-item style="width: 100%">
                <el-button
                    type="primary"
                    style="width: 100%"
                    @click="handleLogin"
                    :loading="loading"
                >
                    登录
                </el-button>
            </el-form-item>
        </el-form>
    </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import request from '../utils/request'

const router = useRouter()
const loginFormRef = ref(null)
const loading = ref(false)
const captcha = ref({ id: '', image: '' })
const autoLogin = ref(false)

// 表单数据
const loginForm = reactive({
    username: '',
    password: '',
    captchaId: '',
    captchaCode: '',
})

// 表单校验规则
const loginRules = {
    username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    captchaCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
}

// 获取验证码
const getCaptcha = async () => {
    try {
        const res = await request.get('/auth/captcha')
        captcha.value = res.data
        loginForm.captchaId = res.data.id
    } catch (error) {
        ElMessage.error('获取验证码失败')
    }
}

// 登录逻辑
const handleLogin = async () => {
    await loginFormRef.value.validate(async (valid) => {
        if (valid) {
            loading.value = true
            try {
                const res = await request.post('/auth/login', {
                    username: loginForm.username,
                    password: loginForm.password,
                    captcha_id: loginForm.captchaId,
                    captcha_code: loginForm.captchaCode,
                })
                // 存储令牌
                localStorage.setItem('access_token', res.data.access_token)
                localStorage.setItem('refresh_token', res.data.refresh_token)
                localStorage.setItem('currentUser', loginForm.username)
                // 跳转首页
                router.push('/home')
                ElMessage.success('登录成功')
            } catch (error) {
                getCaptcha() // 登录失败刷新验证码
            } finally {
                loading.value = false
            }
        }
    })
}

// 页面加载时获取验证码
onMounted(() => {
    getCaptcha()
    // 已登录则跳转首页
    if (localStorage.getItem('access_token')) {
        router.push('/home')
    }
})
</script>

<style scoped>
.auth-layout {
    width: 100%;
    height: 100vh;
    background-color: #f5f7fa;
    display: flex;
    justify-content: center;
    align-items: center;
}
.login-card {
    width: 400px;
    padding: 30px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
.login-title {
    text-align: center;
    margin-bottom: 20px;
    color: #303133;
}
.captcha-image {
    width: 120px;
    height: 40px;
    cursor: pointer;
    vertical-align: middle;
    border-radius: 4px;
}
</style>